package com.sim.stream.controller;

import cn.hutool.core.util.StrUtil;
import com.sim.stream.service.StreamService;
import com.sim.stream.service.impl.MixedStreamServiceImpl;
import com.sim.stream.service.impl.StreamServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yzf
 */
@RestController
@RequestMapping(value = "/stream")
public class StreamController {

    private static final Logger logger = LoggerFactory.getLogger(StreamController.class);

    @Resource(type = StreamServiceImpl.class)
    private StreamService streamService;

    /**
     * 推流开始或者结束通知
     * @param request
     * @return
     */
    @GetMapping("/publish")
    public String publish(HttpServletRequest request){
        logger.info("推流开始:"+ request.getQueryString());
        String queryStr=request.getQueryString();
        if(StrUtil.isNotEmpty(request.getQueryString())){
            Map<String,String> queryMap=getRequestQuery(queryStr);
            streamService.publish(queryMap);
        }
        return "推流开始";
    }

    /**
     * 推流结束
     * @param requestStr
     * @return
     */
    @PostMapping("/publishDone")
    public String publishDone(@RequestBody String requestStr){
        logger.info("推流结束:"+requestStr);
        streamService.publishDone(requestStr);
        return "推流结束";
    }

    /**
     * 拉流开始或者结束通知
     * @param request
     * @return
     */
    @GetMapping("/play")
    public String play(HttpServletRequest request){
        logger.info("拉流开始:"+request.getQueryString());
        return "拉流开始";
    }

    /**
     * 拉流结束
     * @param requestStr
     * @return
     */
    @PostMapping("/playDone")
    public String playDone(@RequestBody String requestStr){
        logger.info("拉流结束:"+requestStr);
        return "拉流结束";
    }

    private Map<String,String> getRequestQuery(String queryStr) {
        Map<String, String> queryMap = new HashMap<>();
        String[] queryArray=queryStr.split("&");
        for (String query : queryArray) {
            String[] temps = query.split("=");
            queryMap.put(temps[0], temps[1]);
        }
        return queryMap;
    }
}
